﻿using TikTokApp.Interfaces;
namespace TikTokApp.Services
{
    public class TabManager : IDisposable
    {
        private readonly TabControl _tabControl;
        private readonly Dictionary<string, ITabPage> _pages = [];

        public TabManager(TabControl tabControl)
        {
            _tabControl = tabControl ?? throw new ArgumentNullException(nameof(tabControl));
            _tabControl.SelectedIndexChanged += OnTabChanged;
            _tabControl.MouseDown += OnTabMouseDown;
        }
        public void AddPage(ITabPage page)
        {
            ArgumentNullException.ThrowIfNull(page);
            if (_pages.ContainsKey(page.PageTitle)) return;

            // 创建TabPage容器
            var tabPage = new TabPage(page.PageTitle)
            {
                BackColor = SystemColors.Control
            };

            // 添加用户控件
            var userControl = page.AsUserControl();
            userControl.Dock = DockStyle.Fill;
            tabPage.Controls.Add(userControl);

            // 添加到TabControl
            _tabControl.TabPages.Add(tabPage);
            _pages.Add(page.PageTitle, page);

            // 订阅关闭事件
            page.CloseRequested += (s, e) => ClosePage(page.PageTitle);
        }

        public bool ClosePage(string pageTitle)
        {
            if (!_pages.TryGetValue(pageTitle, out var page)) return false;
            if (!page.AllowClose) return false;

            // 查找对应的TabPage
            var tabPage = _tabControl.TabPages
                .Cast<TabPage>()
                .FirstOrDefault(t => t.Text == pageTitle);

            if (tabPage != null)
            {
                // 如果是当前选中页，先切换到其他页
                if (_tabControl.SelectedTab == tabPage)
                {
                    var index = _tabControl.TabPages.IndexOf(tabPage);
                    var newIndex = index == 0 ? 1 : index - 1;
                    if (newIndex < _tabControl.TabPages.Count)
                    {
                        _tabControl.SelectedIndex = newIndex;
                    }
                }

                // 移除页面
                _tabControl.TabPages.Remove(tabPage);
                page.Dispose();
                _pages.Remove(pageTitle);
                return true;
            }

            return false;
        }

        private void OnTabChanged(object sender, EventArgs e)
        {
            // 通知前一个页面失活
            if (_tabControl.SelectedIndex >= 0)
            {
                var previousTab = _tabControl.SelectedTab;
                if (previousTab != null && _pages.TryGetValue(previousTab.Text, out var prevPage))
                {
                    prevPage.OnPageDeactivated();
                }
            }

            // 通知新页面激活
            if (_tabControl.SelectedIndex >= 0)
            {
                var currentTab = _tabControl.SelectedTab;
                if (currentTab != null && _pages.TryGetValue(currentTab.Text, out var currentPage))
                {
                    currentPage.OnPageActivated();
                }
            }
        }

        private void OnTabMouseDown(object sender, MouseEventArgs e)
        {
            // 处理右键关闭标签页
            for (int i = 0; i < _tabControl.TabPages.Count; i++)
            {
                var tabRect = _tabControl.GetTabRect(i);
                if (tabRect.Contains(e.Location) && e.Button == MouseButtons.Right)
                {
                    var tabPage = _tabControl.TabPages[i];
                    if (_pages.TryGetValue(tabPage.Text, out var page))
                    {
                        ClosePage(page.PageTitle);
                    }
                    break;
                }
            }
        }

        public void Dispose()
        {
            _tabControl.SelectedIndexChanged -= OnTabChanged;
            _tabControl.MouseDown -= OnTabMouseDown;

            foreach (var page in _pages.Values)
            {
                page.Dispose();
            }
            _pages.Clear();
        }
    }
}
